﻿import { ipcMain } from 'electron'
import { spawn } from 'child_process'
import { IProcessResult, IProcessOptions } from '../../preload/index.d'

export function setupChildProcessHandlers(): void {
  ipcMain.handle('childProcess.exec', async (event, command: string, options?: IProcessOptions) => {
    try {
      // 根据平台选择执行器
      const isWin = process.platform === 'win32'
      const shell = isWin ? 'cmd.exe' : '/bin/bash'
      const args = isWin ? ['/c', command] : ['-c', command]

      // 设置环境变量
      const env = {
        ...process.env,
        TERM: 'xterm-256color',
        FORCE_COLOR: '1',
        PATH: process.env.PATH || '',
        HOME: process.env.HOME || '',
        SHELL: process.env.SHELL || '/bin/bash'
      }

      console.log('[DEBUG] 主进程执行命令:', command)
      console.log('[DEBUG] 工作目录:', options?.cwd)

      return new Promise<IProcessResult>((resolve) => {
        // 创建子进程
        const child = spawn(shell, args, {
          cwd: options?.cwd,
          env,
          stdio: ['ignore', 'pipe', 'pipe']
        })

        let stdout = ''
        let stderr = ''

        // 处理标准输出
        child.stdout?.on('data', (data) => {
          const str = data.toString()
          stdout += str
          console.log('[DEBUG] 主进程 stdout:', str)
          if (options?.onOutput) {
            event.sender.send('childProcess.output', {
              type: 'stdout',
              data: str
            })
          }
        })

        // 处理标准错误
        child.stderr?.on('data', (data) => {
          const str = data.toString()
          stderr += str
          console.log('[DEBUG] 主进程 stderr:', str)
          if (options?.onOutput) {
            event.sender.send('childProcess.output', {
              type: 'stderr',
              data: str
            })
          }
        })

        // 处理进程结束
        child.on('close', (code) => {
          console.log('[DEBUG] 主进程执行完成，退出码:', code)
          const result: IProcessResult = {
            code,
            stdout,
            stderr
          }
          console.log('[DEBUG] 主进程返回结果:', result)
          resolve(result)
        })

        // 处理错误
        child.on('error', (err) => {
          console.error('[DEBUG] 主进程执行错误:', err)
          const result: IProcessResult = {
            code: 1,
            stdout,
            stderr,
            error: err.message
          }
          console.log('[DEBUG] 主进程返回错误结果:', result)
          resolve(result)
        })
      })
    } catch (error) {
      console.error('[DEBUG] 主进程执行异常:', error)
      return {
        code: 1,
        stdout: '',
        stderr: '',
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  ipcMain.handle('childProcess.spawn', async (event, command: string, args: string[], options?: IProcessOptions) => {
    try {
      // 设置环境变量
      const env = {
        ...process.env,
        TERM: 'xterm-256color',
        FORCE_COLOR: '1',
        PATH: process.env.PATH || '',
        HOME: process.env.HOME || '',
        SHELL: process.env.SHELL || '/bin/bash'
      }

      console.log('[DEBUG] 主进程执行命令:', command, args)
      console.log('[DEBUG] 工作目录:', options?.cwd)

      return new Promise<IProcessResult>((resolve) => {
        // 创建子进程
        const child = spawn(command, args, {
          cwd: options?.cwd,
          env,
          stdio: ['ignore', 'pipe', 'pipe']
        })

        let stdout = ''
        let stderr = ''

        // 处理标准输出
        child.stdout?.on('data', (data) => {
          const str = data.toString()
          stdout += str
          console.log('[DEBUG] 主进程 stdout:', str)
          if (options?.onOutput) {
            event.sender.send('childProcess.output', {
              type: 'stdout',
              data: str
            })
          }
        })

        // 处理标准错误
        child.stderr?.on('data', (data) => {
          const str = data.toString()
          stderr += str
          console.log('[DEBUG] 主进程 stderr:', str)
          if (options?.onOutput) {
            event.sender.send('childProcess.output', {
              type: 'stderr',
              data: str
            })
          }
        })

        // 处理进程结束
        child.on('close', (code) => {
          console.log('[DEBUG] 主进程执行完成，退出码:', code)
          const result: IProcessResult = {
            code,
            stdout,
            stderr
          }
          console.log('[DEBUG] 主进程返回结果:', result)
          resolve(result)
        })

        // 处理错误
        child.on('error', (err) => {
          console.error('[DEBUG] 主进程执行错误:', err)
          const result: IProcessResult = {
            code: 1,
            stdout,
            stderr,
            error: err.message
          }
          console.log('[DEBUG] 主进程返回错误结果:', result)
          resolve(result)
        })
      })
    } catch (error) {
      console.error('[DEBUG] 主进程执行异常:', error)
      return {
        code: 1,
        stdout: '',
        stderr: '',
        error: error instanceof Error ? error.message : String(error)
      }
    }
  })

  ipcMain.handle('childProcess.getEnv', () => {
    return process.env
  })
}
